<script setup>
import CmpAdd from '@/views/liteflow/cmp/CmpAdd.vue'
import CmpEdit from '@/views/liteflow/cmp/CmpEdit.vue'
import axios from '@axios'
import { reactive, ref } from 'vue'
import { VDataTableServer } from 'vuetify/labs/VDataTable'

const componentId = ref()
const componentName = ref()
const type = ref()

const totalPage = ref(1)
const totalCmps = ref(0)
const cmps = ref([])

const options = ref({
  page: 1,
  itemsPerPage: 10,
  sortBy: [],
  groupBy: [],
  search: undefined,
})

const nodeTypeList = reactive([])

const nodeTypeSelect = () => {
  axios.post('/liteflow/cmp/type/options', { }).then(r => {
    nodeTypeList.push(...r.data.data)
  }).catch(e => {
    console.error(e)
  })
}

onMounted(() => {
  nodeTypeSelect()
})

// 表头
const headers = [
  {
    title: '组件ID',
    key: 'componentId',
  },
  {
    title: '组件名称',
    key: 'componentName',
  },
  {
    title: '组件类型',
    key: 'type',
  },
  {
    title: 'Java类',
    key: 'clazz',
  },
  {
    title: 'EL表达式',
    key: 'el',
  },
  {
    title: '操作',
    key: 'actions',
    sortable: false,
  },
]

const fetchCmps = () => {
  axios.post('/liteflow/cmp/page', {
    // q: searchQuery.value,
    type: type.value,
    componentName: componentName.value,
    componentId: componentId.value,
    options: options.value,
  }).then(r => {
    let response = r.data.data
    cmps.value = response.list
    totalPage.value = response.totalPage
    totalCmps.value = response.totalRow
    options.value.page = response.page
  }).catch(e => {
    console.error(e)
  })
}

watchEffect(fetchCmps)



// 👉 List
const cmpListMeta = [
  {
    icon: 'tabler-user-plus',
    color: 'error',
    title: '全部组件',
    stats: '0',
    percentage: +0,
  },
  {
    icon: 'tabler-user-check',
    color: 'success',
    title: '动态组件',
    stats: '0',
    percentage: -0,
  },
  {
    icon: 'tabler-user-exclamation',
    color: 'warning',
    title: '脚本组件',
    stats: '0',
    percentage: +0,
  },
  {
    icon: 'tabler-user',
    color: 'primary',
    title: '其他组件',
    stats: '0',
    percentage: +0,
  },
]


const deleteCmpId = ref('')
const isDeleteDialogVisible = ref(false)

const deleteCmp = id => {
  isDeleteDialogVisible.value = true
  deleteCmpId.value = id
}

const deleteAgreeCmp = id => {
  
  axios.post('/liteflow/cmp/delete', { 
    componentId: deleteCmpId.value,
  }).then(r => {
    fetchCmps()
    isDeleteDialogVisible.value = false
    deleteCmpId.value = ''
  }).catch(e => {
    console.error(e)
  })
}

const isCmpVisible = ref(false)
const addVisible = ref(false)
const addMsg = ref('')
const addMsgColor = ref('error')

const addNewCmp = cmpData => {
  axios.post('/liteflow/cmp/add', cmpData).then(r => {
    if(200 == r.data.code){
      addVisible.value = true
      addMsg.value = r.data.message
      addMsgColor.value = 'success'
    }else{
      addVisible.value = true
      addMsg.value = r.data.message
      addMsgColor.value = 'error'
    }
    fetchCmps()
  }).catch(e => {
    console.error(e)
  })
}


const editKey = ref(1)
const isCmpEditVisible = ref(false)
const editData = ref({})

const updateCmp = cmp => {
  editKey.value ++
  isCmpEditVisible.value = true
  editData.value = cmp
}

const updateCurrCmp = cmpData2 => {
  axios.post('/liteflow/cmp/update', cmpData2).then(r => {
    if(200 == r.data.code){
      addVisible.value = true
      addMsg.value = r.data.message
      addMsgColor.value = 'success'
    }else{
      addVisible.value = true
      addMsg.value = r.data.message
      addMsgColor.value = 'error'
    }
    fetchCmps()
  }).catch(e => {
    console.error(e)
  })
}

const isExecVisible = ref(false)
const execResult = ref('')
const execStatus = ref(200)

const execCmp = cmp => {
  axios.post('/liteflow/cmp/exec', {
    id: cmp.id,
  }).then(r => {
    isExecVisible.value = true
    if(200 == r.data.code){
      execStatus.value = 200
      execResult.value = r.data.data
    }else{
      execStatus.value = 500
      execResult.value = r.data.message
    }
  }).catch(e => {
    console.error(e)
  })
}
</script>

<template>
  <section>
    <VRow>
      <VCol
        v-for="meta in cmpListMeta"
        v-if="false"
        :key="meta.title"
        cols="10"
        sm="6"
        lg="3"
      >
        <VCard>
          <VCardText class="d-flex justify-space-between">
            <div>
              <span>{{ meta.title }}</span>
              <div class="d-flex align-center gap-2 my-1">
                <h6 class="text-h4">
                  {{ meta.stats }}
                </h6>
                <span :class="meta.percentage > 0 ? 'text-success' : 'text-error'">( {{ meta.percentage > 0 ? '+' : '' }}{{ meta.percentage }})</span>
              </div>
              <!-- <span>{{ meta.subtitle }}</span> -->
            </div>

            <VAvatar
              rounded
              variant="tonal"
              :color="meta.color"
              :icon="meta.icon"
            />
          </VCardText>
        </VCard>
      </VCol>

      <VSnackbar
        v-model="addVisible"
        location="top"
        :color="addMsgColor"
      >
        {{ addMsg }}
      </VSnackbar>

      <VCol cols="12">
        <VCard title="检索组件">
          <!-- 👉 Filters -->
          <VCardText>
            <VRow>
              <!-- 👉 Select Role -->
              <VCol
                cols="12"
                sm="4"
              >
                <VTextField
                  v-model="componentId"
                  label="组件ID"
                  clearable
                />
              </VCol>
              <!-- 👉 Select Plan -->
              <VCol
                cols="12"
                sm="4"
              >
                <VTextField
                  v-model="componentName"
                  label="组件名称"
                  clearable
                />
              </VCol>
              <VCol
                cols="12"
                sm="4"
              >
                <VSelect
                  v-model="type"
                  label="组件类型"
                  :items="nodeTypeList"
                  clearable
                  clear-icon="tabler-x"
                />
              </VCol>
            </VRow>
          </VCardText>

          <VDivider />

          <VCardText class="d-flex flex-wrap py-4 gap-4">
            <div class="me-3 d-flex gap-3">
              <AppSelect
                :model-value="options.itemsPerPage"
                :items="[
                  { value: 10, title: '10' },
                  { value: 20, title: '20' },
                  { value: 50, title: '50' },
                  { value: 100, title: '100' },
                ]"
                style="width: 6.25rem;"
                @update:model-value="options.itemsPerPage = parseInt($event, 10)"
              />
            </div>
            <VSpacer />

            <div class="d-flex align-center flex-wrap gap-4">
              <VBtn
                prepend-icon="tabler-plus"
                @click="isCmpVisible = true"
              >
                新增组件
              </VBtn>
            </div>
          </VCardText>

          <VDivider />

          <!-- SECTION datatable -->
          <VDataTableServer
            v-model:items-per-page="options.itemsPerPage"
            v-model:page="options.page"
            :items="cmps"
            :items-length="totalCmps"
            :headers="headers"
            class="text-no-wrap"
            @update:options="options = $event"
          >
            <!-- Plan -->
            <template #item.componentId="{ item }">
              <span class="font-weight-medium">{{ item.raw.componentId }}</span>
            </template>

            <template #item.componentName="{ item }">
              <span class="font-weight-medium">{{ item.raw.componentName }}</span>
            </template>

            <template #item.type="{ item }">
              <span class="font-weight-medium"><VChip
                label
                color="success"
                size="small"
              >  {{ item.raw.type }} </VChip></span>
            </template>

            <template #item.clazz="{ item }">
              <span class="font-weight-medium">{{ item.raw.clazz }}</span>
            </template>

            <template #item.el="{ item }">
              <VBtn
                variant="plain"
                size="small"
                style="padding-left: 0;"
              >
                查看EL表达式
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  {{ item.raw.el }}
                </VTooltip>
              </VBtn>
              <!-- <span class="font-weight-medium">{{ item.raw.el }}</span> -->
            </template>

            <!-- Actions -->
            <template #item.actions="{ item }">
              <IconBtn @click="deleteCmp(item.raw.componentId)">
                <VIcon icon="tabler-trash" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  删除
                </VTooltip>
              </IconBtn>

              <IconBtn @click="updateCmp(item.raw)">
                <VIcon icon="tabler-edit" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  编辑
                </VTooltip>
              </IconBtn>

              <IconBtn @click="execCmp(item.raw)">
                <VIcon icon="tabler-player-play-filled" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  调试
                </VTooltip>
              </IconBtn>
            </template>

            <!-- pagination -->
            <template #bottom>
              <VDivider />
              <div class="d-flex align-center justify-sm-space-between justify-center flex-wrap gap-3 pa-5 pt-3">
                <p class="text-sm text-disabled mb-0" />
                <VPagination
                  v-model="options.page"
                  :length="Math.ceil(totalCmps / options.itemsPerPage)"
                  :total-visible="$vuetify.display.xs ? 1 : Math.ceil(totalCmps / options.itemsPerPage)"
                >
                  <template #prev="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      上一页
                    </VBtn>
                  </template>

                  <template #next="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      下一页
                    </VBtn>
                  </template>
                </VPagination>
              </div>
            </template>
          </VDataTableServer>
          <!-- SECTION -->
        </VCard>

        <!-- 👉 新增组件 -->
        <CmpAdd
          v-model:isDrawerOpen="isCmpVisible"
          @cmp-data="addNewCmp"
        />

        <!-- 编辑组件 -->
        <CmpEdit
          :key="editKey"
          v-model:isDrawerOpen2="isCmpEditVisible"
          :edit-data="editData"
          @cmp-data2="updateCurrCmp"
        />

        <!-- 删除确认 -->
        <VDialog
          v-model="isDeleteDialogVisible"
          width="300"
        >
          <DialogCloseBtn @click="isDeleteDialogVisible = !isDeleteDialogVisible" />
          <VCard title="提示">
            <VCardText> 是否删除组件[{{ deleteCmpId }}]？ </VCardText>
            <VCardText class="d-flex justify-end gap-3 flex-wrap">
              <VBtn
                color="secondary"
                variant="tonal"
                @click="isDeleteDialogVisible = false"
              >
                取消
              </VBtn>
              <VBtn @click="deleteAgreeCmp">
                确定
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>

        <VSnackbar
          v-model="isExecVisible"
          multi-line
        >
          <span v-if="execStatus == 200">执行成功：</span>
          <span v-if="execStatus != 200">执行失败：</span>
          <br>
          {{ execResult }}
          <template #actions>
            <VBtn
              color="error"
              @click="isExecVisible = false"
            >
              关闭
            </VBtn>
          </template>
        </VSnackbar>
      </vcol>
    </vrow>
  </section>
</template>

<style lang="scss">
.text-capitalize {
  text-transform: capitalize;
}

.user-list-name:not(:hover) {
  color: rgba(var(--v-theme-on-background), var(--v-medium-emphasis-opacity));
}
</style>
